const express = require('express')
const mongoose = require('mongoose')

const bcrypt = require('bcryptjs')
const Category = require('../../models/category')
const User = require('../../models/user')
const TaskAudit = require('../../models/taskaudit')
const Task = require('../../models/task')
const Journal = require('../../models/journal')
const Admin = require('../../models/admin')

//结果处理工具
const response = require('../../utils/response')
const {
    setparentid
} = require('../../utils/tool')

const router = express.Router();

//获取职位
router.get('/positionCate', async (req, res) => {
    let data = []
    let one = await Category.findOne({
        name: '院长'
    }).lean()
    data.push(one)
    async function getPosition(id, data = []) {
        let one2 = await Category.findOne({
            parentId: id
        })
        if (one2) {
            data.push(one2)
            await getPosition(one2._id, data)
        }
    }
    await getPosition(one._id, data)
    res.send(data)
})

//获取专业
router.get('/proCate', async (req, res) => {
    let {
        _id
    } = await Category.findOne({
        name: '人工智能'
    })
    let data = await Category.find({
        parentId: _id
    })
    res.send(data)
})

//获取全部成员
router.get('/users', async (req, res) => {
    let data = await User.find({}, {
        name: 1
    }).populate('position', ['name']).populate('rofessional', ['name'])
    res.send(data)
})

//获取老师的成员
router.get('/teacharUser', async (req, res) => {
    let {
        _id
    } = await Category.findOne({
        name: '普通老师'
    })
    let data = await User.find({
        position: _id
    })
    res.send(data)
})

//获取专业带头人成员
router.get('/bossUser', async (req, res) => {
    let {
        _id
    } = await Category.findOne({
        name: '专业带头人'
    })
    let data = await User.find({
        position: _id
    })
    res.send(data)
})

//帮助负责人审核任务
router.put('/helpTask', async (req, res) => {
    let {
        status
    } = req.body
    //校验
    if (status === 1) {
        response(res, 401, '此任务已审核，请检查任务状态~~', null)
        return
    }

    req.body.status = 1
    const model = await TaskAudit.findByIdAndUpdate(req.body._id, req.body)

    response(res, 200, '成功', model)
})

//打回任务接口
router.put('/return', async (req, res) => {
    let data = req.body
    //校验
    if (data.status === 2) return res.status(422).send({
        message: '该任务已被退回~~'
    })
    data.status = 2
    data.void = 1
    const model = await TaskAudit.findByIdAndUpdate(data._id, data)

    let taskOne = await Task.findById(data.taskId).lean()
    taskOne.status = 2
    await Task.findByIdAndUpdate(taskOne._id, taskOne)

    response(res, 200, '成功', model)
})

//获取父级任务选择
router.get('/parentTask', async (req, res) => {


    var task1 = await Task.find({
            grade: 0
        })
        .populate('worker', ['name'])
        .populate('creator', ['name'])
        .sort({
            _id: -1
        })
        .lean()
    var arr = []
    async function taskLoop(loop, grade) {
        for (let i = 0; i < loop.length; i++) {
            let task1 = await Task.find({
                    parentId: loop[i]._id,
                    grade: grade
                })
                .populate('worker', ['name'])
                .populate('creator', ['name'])
                .lean()
            loop[i].children = task1

            var loop2 = loop[i].children
            if (task1.length == 0) {
                delete loop[i].children
            }
            await taskLoop(loop2, grade * 1 + 1)
        }
        arr.push(loop)
    }
    await taskLoop(task1, 1)
    task = arr[arr.length - 1]
    res.send(task)
})

//根据查询id查询任务层级
router.get('/taskParentid', async (req, res) => {
    let {
        parentId,
        grade,
        _id
    } = req.query
    let data = []
    grade = parseInt(grade)

    await setparentid(grade - 1, parentId, data)
    res.send(data)
})

//获取父级分类选择
router.get('/cateParent', async (req, res) => {

    var cate1 = await Category.find({
            grade: 0
        })
        .sort({
            _id: -1
        })
        .lean()
    var arr = []
    async function cateLoop(loop, grade) {
        for (let i = 0; i < loop.length; i++) {
            let cate2 = await Category.find({
                parentId: loop[i]._id,
                grade: grade
            }).lean()
            if (cate2.length > 0) {
                loop[i].children = cate2
                var loop2 = loop[i].children
                await cateLoop(loop2, grade * 1 + 1)
            }
        }
        arr.push(loop)
    }
    await cateLoop(cate1, 1)
    let cate = arr[arr.length - 1]
    res.send(cate)
})

//根据任务id获取负责人信息
router.get('/taskWorkers/:taskId', async (req, res) => {
    const taskId = req.params.taskId
    let {
        worker
    } = await Task.findById(taskId).populate("worker").lean()

    let model = []
    for (let i in worker) {
        let user = await User.findById(worker[i]._id).populate("position rofessional").lean()
        model.push(user)
    }

    res.send(model)
})

// 添加管理员
router.post('/adminUser', async (req, res) => {
    let username = req.body.username
    let password = req.body.password
    let data = await Admin.find({
        username
    })
    if (data.length != 0) {
        response(res, 402, '用户名已存在', data)
    } else {
        var admin = new Admin()
        admin.username = username
        admin.password = password
        await admin.save()
        response(res, 200, '添加管理员成功', admin)
    }
})

// 修改密码
router.post('/adminUserModify', async (req, res) => {
    var username = req.body.username
    var oldPassword = req.body.oldPassword
    var newPassword = req.body.newPassword
    var data = await Admin.findOne({
        username
    })
    if (!bcrypt.compareSync(oldPassword, data.password)) {
        response(res, 422, '密码错误！！！')
    } else {
        data.password = newPassword
        await data.save()
        response(res, 200, '修改密码成功', data)
    }
})

// 搜索
router.get('/search', async (req, res) => {
    let {
        pagenum,
        pagesize,
        query
    } = req.query
    pagenum = parseInt(pagenum)
    pagesize = parseInt(pagesize)
    let model = await Task.find({
        taskname: {
            $regex: query
        }
    }).populate('worker', ['name']).populate('creator', ['name']).sort({
        _id: -1
    }).skip((pagenum - 1) * pagesize).limit(pagesize).lean()

    //总数
    let total = await Task.find({
        grade: 0,
        taskname: {
            $regex: query
        }
    }).count()

    response(res, 200, '获取任务列表成功', {
        pagenum,
        total,
        model
    })
})


// 首页折线图表
router.get('/statistical', async (req, res, next) => {

    let tasks = await Task.find({
        grade: 0
    })
    // 过滤字段
    tasks = tasks.map(v => {
        return {
            _id: v._id,
            taskname: v.taskname,
        }
    })

    for (let i in tasks) {
        let journal = await Journal.find({
            taskId: tasks[i]._id
        }).lean()
        journal = journal.map(v => {
            let time = new Date(v.createdAt)
            let month = time.getMonth()
            let year = time.getFullYear()
            if (month === 0) {
                month = 12
            }
            return {
                _id: v._id,
                process: v.newData[0].process,
                month: year + '/' + month
            }
        })
        tasks[i].journal = journal
    }

    // 排序
    for (let a in tasks) {
        tasks[a].journal.sort(function (a, b) {
            let time1 = new Date(b.month)
            let time2 = new Date(a.month)
            return time1 < time2 ? 1 : -1
        })
    }
    //  tasks.sort(function (a, b) {
    //      return b.createTime < a.createTime ? 1 : -1
    //  })

    // res.send(tasks)
    response(res, 200, '获取统计成功~~', tasks)


})

module.exports = router